//
//  InterfaceMode.swift
//  beegin
//
//  Created by zsy on 15/10/4.
//  Copyright © 2015年 kszz. All rights reserved.
//

import Foundation


public protocol ServerResponseDelegete : NSObjectProtocol{
    
    func ServerResponseWithJSON(keyPath:String,method:String,jsonResp:JSON?,errorMsg:String?,typeid:Int?)
}

class ASIPointRequest:ASIFormDataRequest {
    
    var keyString:String?
    var typeid:Int?
    var method:String!
}

@objc protocol CustomerResponseDelegete {
    optional func RegisterResponse(result: Int,message:String?)
    optional func LoginResponse(result: Int,message:String?,customer:BeeginCusomer)
    optional func RegisterBaby(result: Int,message:String?,customer:BeeginCusomer)
}


class BeeginCusomer : NSObject,ServerResponseDelegete{
    
    var customerDelegete:CustomerResponseDelegete?
    var servInterface:InterfaceMode = InterfaceMode()

    
    //当前数据获取时间片
    var dataFetchDict:[String:NSDate] = [:]
    
    var RecordDate:NSDate = NSDate()
    
    override init(){
        super.init()
        
        autoLogin()
        servInterface.servResponseDelegete = self
       reloadFoods(nil)
    }
    
    var customerId:Int = -1
    var currentBabyId:Int = -1
    var serverLoginState:Bool = false
    
    var loginInfo: [String : String]?{
    
        get{
            return NSUserDefaults.standardUserDefaults().objectForKey(Constants.loginInfo) as? [String : String]
        }set{
        
             NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: Constants.loginInfo)
        }
    }
    
    func JoinKEYID(key:String,_ id:Int)->String{
    
        return "\(key)/\(id)"
    }

    
    //客户信息
    var CustomerInfo:CustomerEntity?{
    
        get{
            if let data = NSUserDefaults.standardUserDefaults().objectForKey(JoinKEYID(Constants.customPath,customerId)) as? [String:AnyObject]{
            
                return CustomerEntity(data)
            }
            
            return nil
        }
    }
    //BB信息
    var BabyInfo:BabyEntity?{
        
        get{
            if let data = NSUserDefaults.standardUserDefaults().objectForKey(JoinKEYID(Constants.babyPath,customerId)) as? [String:AnyObject]{
                
                return BabyEntity(data)
            }
            
            return nil
        }
        
        
    }
    //记录信息
    var Records:[RecordEntity]{
    
        var localRecords:[RecordEntity] = []
        if let dataArray = NSUserDefaults.standardUserDefaults().objectForKey(JoinKEYID(Constants.recordPath,customerId)) as? [[String:AnyObject]]{
            
            for data in dataArray{
                
                let foods = Food.filter{
                
                    return ($0.id == (data["foodid"] as? Int) ?? -1)
                }
                
                if !foods.isEmpty{
                
                    localRecords.append(RecordEntity(food: foods[0],currentBabyId,data))
                }
            }
        }
        
        localRecords.sortInPlace {
            
            return $0.record_time.compare($1.record_time) == NSComparisonResult.OrderedAscending
        }
        
        return localRecords
    }
    
    var activeRecords:[RecordEntity]{
        
        let format = NSDateFormatter()
        format.dateFormat = "yyyy-MM-dd"
        let setDateString = format.stringFromDate(NSDate(timeInterval: 8 * 60 * 60, sinceDate: RecordDate))
        return Records.filter{
            
            let recordDateString = format.stringFromDate(NSDate(timeInterval: 8 * 60 * 60, sinceDate: $0.record_time))
            
            return $0.state == 1 && setDateString == recordDateString
        }
    }
    var historyRecords:[FoodEntity]{
        var result:[FoodEntity] = []
        
        result.append(self.Water)
        result.append(self.Breast)
               
        var fids:[Int] = [result[0].id,result[1].id]
        
        Records.forEach{
            if !fids.contains($0.record_food.id){
                result.append($0.record_food)
                fids.append($0.record_food.id)
            }
        }
        
        return result
    }
    
    //收藏信息
    var Favorites:[FavoriteEntity]{
        
        var localFavorites:[FavoriteEntity] = []
        if let dataArray = NSUserDefaults.standardUserDefaults().objectForKey(JoinKEYID(Constants.favoritePath,customerId)) as? [[String:AnyObject]]{
            
            for data in dataArray{
                
                localFavorites.append(FavoriteEntity(data))
            }
        }
        return localFavorites
    }
    
    //食物信息
    var foodsCache :[FoodEntity] = defaultFoods
    
    func updateLocalFoods(foodDic:[[String:AnyObject]]){

        NSUserDefaults.standardUserDefaults().setObject(foodDic, forKey: JoinKEYID(Constants.foodPath, customerId))
        
        reloadFoods(foodDic)
    }
    
    func reloadFoods(foodDic:[[String:AnyObject]]?){
    
        let dataArray = foodDic ?? NSUserDefaults.standardUserDefaults().objectForKey(JoinKEYID(Constants.foodPath, customerId)) as? [[String:AnyObject]]
        
        if dataArray != nil{
            foodsCache.removeAll()
            for data in dataArray!{
                
                foodsCache.append(FoodEntity(data))
            }
        }
    }
    
    func replaceFood(foodDic:[String:AnyObject]){
        
        if var dataArray = NSUserDefaults.standardUserDefaults().objectForKey(JoinKEYID(Constants.foodPath, customerId)) as? [[String:AnyObject]]{
        
            var index = -1
            for k in 0...dataArray.count - 1{
                
                if let id = dataArray[k]["id"] as? Int{
                
                    if id == (foodDic["id"] as? Int){
                        index = k
                        break
                    }
                }
            }
            
            if index == -1{
            
                dataArray.append(foodDic)
            }else{
            
                 dataArray[index] = foodDic
            }
            
            reloadFoods(dataArray)
        }
    }
    
    var Food:[FoodEntity]{
        
        if needServerFetch(Constants.foodPath) && customerId != -1{
        
            servInterface.ASIGetOrDelData(customerId, key: Constants.foodPath)
        }
        
        return foodsCache
    }
    
    var Water:FoodEntity{
    
        return FoodEntity(["id" : 1,"typeid" : 1,"name" : "白开水"])
    }
    var Breast:FoodEntity{
        return FoodEntity(["id" : 2,"typeid" : 2,"name" : "母乳"])
    }
    
    //食材信息
    var Material:[MaterialEntity]{
        
        var localMaterials:[MaterialEntity] = []
        
        if let dataArray = NSUserDefaults.standardUserDefaults().objectForKey(Constants.materialPath) as? [[String:AnyObject]]{
            
            for data in dataArray{
                
                localMaterials.append(MaterialEntity(data))
            }
            
        }else{
            
//            localMaterials = defaultBrands
        }
        
        if needServerFetch(Constants.materialPath){
            
            servInterface.ASIGetOrDelData(1, key: Constants.materialPath)
        }
        
        return localMaterials
    }
    
    //食材信息
    var CustomeFood:[CustomFoodEntity]{
        
        var localCustomes:[CustomFoodEntity] = []
        
        if let dataArray = NSUserDefaults.standardUserDefaults().objectForKey(Constants.customPath) as? [[String:AnyObject]]{
            
            for data in dataArray{
                
                localCustomes.append(CustomFoodEntity(dic: data))
            }
            
        }else{
            
            //            localMaterials = defaultBrands
        }
        
        if needServerFetch(Constants.customPath){
            
            servInterface.ASIGetOrDelData(1, key: Constants.customPath)
        }
        
        return localCustomes
    }
    
    //区域信息
    lazy var Orgin:[OrginEntity] = {
        
        var localOrgin:[OrginEntity] = []
        
        if let dataArray = NSUserDefaults.standardUserDefaults().objectForKey(Constants.orginPath) as? [[String:AnyObject]]{
            
            for data in dataArray{
                
                localOrgin.append(OrginEntity(data))
            }
            
        }else{
            
            localOrgin = defaultOrgins
        }
        
        if self.needServerFetch(Constants.brandPath){
            
            self.servInterface.ASIGetOrDelData(1, key: Constants.orginPath)
        }
        
        return localOrgin
    }()
    
    //元素信息
    func getFoodElementsDic(foodid:Int)->[String:AnyObject]?{
    
        let keyString = "Elements\(foodid)"
        
        if let dataDic = NSUserDefaults.standardUserDefaults().objectForKey(keyString) as? [String:AnyObject]{
        
            return dataDic
        }
        
        if let json = servInterface.ASIGetServerData(Constants.foodElementsPath + foodid.description){
        
            if let data = json["data"].dictionary{
                
                if let dic = data["elementData"]?.dictionaryObject{
                
                    print("get food elements \(foodid):\(dic)")
                    NSUserDefaults.standardUserDefaults().setObject(dic, forKey: keyString)
                    
                    return dic
                }
            }
        }
        
        return nil
    }
    
    func customeFoodFormulals(foodid:Int)->[FormulalEntity]{
        
        let keyString = "Formulals\(foodid)"
        
        var formulals:[FormulalEntity] = []
        if let dataArray = NSUserDefaults.standardUserDefaults().objectForKey(keyString) as? [[String:AnyObject]]{
        
            for data in dataArray{
                
                formulals.append(FormulalEntity(dic: data))
            }
        }else
            if let json = servInterface.ASIGetServerData(Constants.customPath + foodid.description){
            
            if let data = json["data"].dictionary{
                
                if let array = data["formulaDatas"]?.array{
                
                    var arrayFormulalsData:[[String:AnyObject]] = []
                    for formulalJson in array{
                    
                        if let formulalData = formulalJson.dictionaryObject{
                            
                            let formulal = FormulalEntity(dic: formulalData)
                            if formulal.sort == 0{
                            
                                formulals.insert(formulal, atIndex: 0)
                                arrayFormulalsData.insert(formulalData, atIndex: 0)
                                
                            }else{
                                formulals.append(formulal)
                                arrayFormulalsData.append(formulalData)
                            }
                        }
                    }
                    
                    NSUserDefaults.standardUserDefaults().setObject(arrayFormulalsData, forKey: keyString)
                }
            }
        }
        
        return formulals
    }
    
    func saveCustomeFood(customeFood:CustomFoodEntity){
         var arrayFormulalsData:[[String:AnyObject]] = []
        for formulal in customeFood.formalals{
        
            arrayFormulalsData.append(formulal.rawDictionary)
        }
        
        NSUserDefaults.standardUserDefaults().setObject(arrayFormulalsData, forKey: "Formulals\(customeFood.id)")
    }
    
    // MARK: - 基础方法
    
    func needServerFetch(keyPath:String)->Bool{
    
        let dateFetch = dataFetchDict[keyPath]
        if dateFetch == nil || NSDate().timeIntervalSinceDate(dateFetch!) > NSTimeInterval(10000){
        
            dataFetchDict[keyPath] = NSDate(timeIntervalSinceNow: -995)
            
            return true
        }
        
        return false
    }
    
    func OrginOfFood(foodid:Int)->String?{
    
        let orgins = Orgin.filter{
        
            return $0.id == foodid
        }
        if !orgins.isEmpty{
        
            return orgins[0].nameEn
        }
        
        return nil
    }
    
    func OrginWithExsistFood(type:FoodType) ->[OrginEntity]{
        
        let foodWithOrgin = FoodWithType(type)
        let ids = foodWithOrgin.map{
        
            return $0.orgin_id
        }
        return Orgin.filter{
        
            let idsString = ids.description
            let range = idsString.rangeOfString($0.id.description)
            
            return range == nil ? false : true
        }
    }
    
    func FoodWithType(type:FoodType)->[FoodEntity]{
    
        return Food.filter{
        
            return $0.typeid == type.rawValue
        }
    }
    
    func FoodWithOrgin(orginid:Int,foodType: FoodType)->[FoodEntity]{
        
        return Food.filter{
            
            return $0.orgin_id == orginid && foodType.rawValue == $0.typeid
        }
    }
    
    func brandWithType(typeid:BrandType)->[BrandEntity]{
    
        var localBrands:[BrandEntity] = []
    
        let keyString = Constants.brandPath + typeid.rawValue.description
        if let dataArray = NSUserDefaults.standardUserDefaults().objectForKey(keyString) as? [[String:AnyObject]]{
            
            for data in dataArray{
                
                localBrands.append(BrandEntity(data))
            }
            
        }else{
            
            localBrands = typeid.rawValue == 1 ? defaultMilkBrands : defaultSuplementBrands
        }
        
        if needServerFetch(keyString){
            
            servInterface.ASIGetOrDelData(typeid.rawValue, key: Constants.brandPath)
        }
        
        return localBrands
    }
    
    func materialWithId(id:Int?)->FoodEntity?{
    
        let foods = Food
        let foodFliters = foods.filter{
        
            return $0.typeid == FoodType.Material.rawValue && $0.id == id
        }
        
        return foodFliters.isEmpty ? nil : foodFliters[0]
    }
    
    func DayOfRecords(date:NSDate?,foodType:FoodType? = nil)->[RecordEntity]{
        
        let recordsDate = date == nil ? RecordDate : date!
        
        let format = NSDateFormatter()
        format.dateFormat = "yyyy-MM-dd"
        let setDateString = format.stringFromDate(NSDate(timeInterval: 8 * 60 * 60, sinceDate: recordsDate))
        return Records.filter{
            
            let recordDateString = format.stringFromDate(NSDate(timeInterval: 8 * 60 * 60, sinceDate: $0.record_time))
            
            return $0.state == 1 &&
                setDateString == recordDateString &&
                (foodType == nil || foodType!.rawValue == $0.record_food.typeid)
        }
    }
    
    
    //MARK: -加载图片
    func setImage(setView:UIView,serverFile:String,gray:Bool = false,defaultImageName:String? = nil){
        
        func imageForView(imageView:UIView,localPath:String)->Bool{
            
            var res = true
            var setImage = UIImage(named: localPath)
            
            if setImage == nil{
                setImage = UIImage(contentsOfFile: localPath)

            }
            
            if setImage == nil{
                if defaultImageName != nil{
                    setImage = UIImage(named: defaultImageName!)
                }
                res = false
            }
            if setImage != nil{
            
                if gray{
                    
                    setImage = OCUtils.getGrayImage(setImage)
                }
                if let view = imageView as? UIButton{
                    view.setImage(setImage, forState: .Normal)
                }else if let view = imageView as? UIImageView{
                    view.image = setImage
                }
            }
            
            return res
        }
        
        if imageForView(setView, localPath: serverFile){
        
            return
        }
        
        let arrayNames = serverFile.componentsSeparatedByString("/")
//        if arrayNames.count == 1{
//        
//            imageForView(setView, localPath: arrayNames[0])
//        }else
        if let fileName = arrayNames.last{
            
            let localPath = "\(OCUtils.documentFolderPath())/\(fileName)"
            if NSFileManager().fileExistsAtPath(localPath){
            
                imageForView(setView, localPath: localPath)
            }else{
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
                    
                    if let serverFileInPath = self.servInterface.ASIGetServerImage(serverFile){
                    
                        if NSFileManager().fileExistsAtPath(serverFileInPath){
                        
                            dispatch_async(dispatch_get_main_queue(), {
                                
                                imageForView(setView, localPath: serverFileInPath)
                            })
                        }
                    }
                })
            }
        }
    }
    
    //上传图片
    func UploadImage(fileName:String,completion:((serverPath:String?) -> Void)?)
    {
        let localPath = OCUtils.documentFolderPath() + "/" + fileName
        
        return servInterface.ASIUploadImage(localPath, completion: { (serverPath) -> Void in
            
            if serverPath != nil{
            
                let arrayNames = serverPath!.componentsSeparatedByString("/")
                if let serverName = arrayNames.last{
                
                    let serverFileInLocalPath = OCUtils.documentFolderPath() + "/" + serverName
                    if NSFileManager().fileExistsAtPath(localPath){
                    
                        rename(localPath, serverFileInLocalPath)
                    }
                }
            }
            
            completion?(serverPath: serverPath)
        })
    }
    
    //MARK: -业务处理
    //登出
    func LoginOut(){
    
        customerId = -1
        loginInfo = ["loginid" : "","password" : ""]
    }
    
    //登录
        
    func autoLogin()->Bool{
    
        if let idString = loginInfo?["customerid"]{
        
            customerId = Int(idString) ?? -1
            if customerId != -1{
            
                if let loginid = loginInfo!["loginid"] {
                
                    if let password = loginInfo!["password"]{
                    
                        loginServer(loginid, password: password)
                    }
                }
            }
        }
        
        
        return customerId != -1
    }
    
    func loginServer(email:String,password:String){
    
        loginInfo = ["loginid" : email,"password" : ""]
        servInterface.setServerData(Constants.loginPath, paramDic: ["loginid":email,"password":password])
    }
    
    
    //用户注册
    private var regPassword = ""
    private var regLoginid = ""
    func register(loginId:String,password:String,nick:String?,imagePath:String?){
    
        regPassword = password
        regLoginid = loginId
        
        var dic = ["loginid":loginId,"password":password]
        if nick != nil{
        
            dic["nickname"] = nick!
        }
        if imagePath != nil{
        
            dic["avatar"] = imagePath!
        }
        servInterface.setServerData(Constants.registerPath, paramDic: dic)
    }
    
    //注册BABY信息
    func registerBaby(baby:BabyEntity){

        servInterface.setServerData(Constants.babyPath, paramDic: baby.rawDictionary)
    }
    
    //修改BABY信息
    func modifyBaby(baby:BabyEntity){
        servInterface.ASIReqeustData(baby.rawDictionary, key: Constants.babyPath, method: "PUT")
    }
    
    //修改 增加喂食记录
    func EditRecord(inout record:RecordEntity){
        
        //更新当前页面未更新记录
        if record.id == -1{
        
            let localRecords = Records.filter{
                
                return $0.syncid == record.syncid
            }
            
            if !localRecords.isEmpty{
            
                record.id = localRecords[0].id
            }
        }

        
        let mtd = record.id == -1 ? "POST" : "PUT"
        servInterface.ASIReqeustData(record.rawDictionary, key: Constants.recordPath, method: mtd)
    }
    func DeleteRecord(id:Int){
    
        servInterface.ASIReqeustData(["id" : id,"_method" : "DELETE"], key: Constants.recordPath, method: "DELETE")
    }
    
    func EditCustomeFood(inout customFood:CustomFoodEntity)->FoodEntity?{
    
        let method = customFood.id == -1 ? "POST" : "PUT"
        if let result = servInterface.ASIReqeustData(customFood.rawDictionary, key: Constants.customPath,method: method,block: true){
            
            let json = JSON(data: result)
            print(json.rawString())
            if let code = json["code"].int{
            
                if code == 0{
                
                    if let dic = json["data"].dictionaryObject{
                    
                        customFood.id = (dic["id"] as? Int) ?? -1
                        self.replaceFood(dic)
                        
                        return FoodEntity(dic)
                    }
                    
                }else{
                
                     let alert = UIAlertView(title: "", message: "服务器请求失败!", delegate: self, cancelButtonTitle: "取消")
                    
                    alert.show()
                }
            }
            
        }
        
        return nil
    }
    
    // 收藏
    func LoadFavriates(){
    
        servInterface.ASIGetOrDelData(customerId, key: Constants.favoritePath)
    }
    
    func EditFavriates(foodid:Int,favariateEnable:Bool){

        let method = favariateEnable ? "POST" : "DELETE"
        let dict = ["customer.id" : customerId,"food.id" : foodid]
        servInterface.ASIReqeustData(dict, key: Constants.favoritePath, method: method,block: favariateEnable)
    }
    
     // MARK: - 服务器数据响应
    func ServerResponseWithJSON(keyPath: String, method:String, jsonResp: JSON?, errorMsg: String?,typeid:Int?) {
        
        var responseType : DataResponseType = .ResponseItem
        
        switch keyPath{
        case Constants.loginPath:
            if let resp = jsonResp?.dictionary{
                
                if var data = resp["data"]?.dictionaryObject{
                    
                    customerId = (data["id"] as? Int) ?? -1
                    
                    if let babyids = data["babiesid"] as? [Int]{
                    
                        if !babyids.isEmpty{
                        
                            currentBabyId = babyids[0]
                        }else{
                        
                            servInterface.ASIGetOrDelData(customerId, key: Constants.babyPath)
                        }
                    }
                    
                    loginInfo = ["loginid" : data["loginid"] as! String,"password" : data["password"] as! String,"customerid" : customerId.description]
                    
                    
                    NSUserDefaults.standardUserDefaults().setObject(data, forKey: JoinKEYID(Constants.customPath, customerId))
                    
                }
                
                if let result = jsonResp?.dictionaryObject{
                    
                    let code  = result["code"] as! Int
                    if code == 0{
                        serverLoginState = true
                        servInterface.ASIGetOrDelData(currentBabyId, key: Constants.babyPath)
                        servInterface.ASIGetOrDelData(customerId, key: Constants.favoritePath)
                    }
                    
                    customerDelegete?.LoginResponse?(result["code"] as! Int, message: result["msg"] as? String, customer: self)
                }
                
            }else{
            
                customerDelegete?.LoginResponse?(-1, message: errorMsg, customer: self)
            }
            
            break
        case Constants.registerPath:
            if let result = jsonResp?.dictionaryObject{
                
                if let data = jsonResp?.dictionary?["data"]?.dictionaryObject{
                
                    customerId = (data["id"] as? Int) ?? -1
                }
                
                customerDelegete?.RegisterResponse?(result["code"] as! Int, message: result["msg"] as? String)
            }else{
            
                customerDelegete?.RegisterResponse?(-1, message: errorMsg)
            }
            break
            
        case Constants.babyPath:
            if let result = jsonResp?.dictionaryObject{
                
                if let data = jsonResp?.dictionary?["data"]?.dictionaryObject{
                    
                    currentBabyId = (data["id"] as? Int) ?? -1
                    
                    NSUserDefaults.standardUserDefaults().setObject(data, forKey: JoinKEYID(Constants.babyPath, customerId))
                }
                
                let code = result["code"] as! Int
                if code == 0{
                
                    servInterface.ASIGetOrDelData(currentBabyId, key: Constants.recordPath)
                }
                
                customerDelegete?.RegisterBaby?(code, message: result["msg"] as? String,customer: self)
            }else{
                
                customerDelegete?.RegisterBaby?(-1, message: errorMsg,customer: self)
            }
            break
        case Constants.brandPath,Constants.orginPath:
            if let result = jsonResp?.dictionary{
                if let dic = result["data"]?.arrayObject{
                    let keyString = typeid == nil ? keyPath : (keyPath + typeid!.description)
                    dataFetchDict[keyString] = NSDate()
                    NSUserDefaults.standardUserDefaults().setObject(dic, forKey: keyString)
                }
            }
            break
            
        case Constants.customPath:
            if let code = jsonResp?.dictionaryObject?["code"] as? Int{
            
                if code == 0{
                    servInterface.ASIGetOrDelData(customerId, key: Constants.foodPath)
                }
            }
    
            break
        case Constants.favoritePath:
            if method == "POST" ||  method == "DELETE"{
                
                LoadFavriates()
                
            }else
            {
                if let result = jsonResp?.dictionary{
                    
                    dataFetchDict[keyPath] = NSDate()
                    if let dic = result["data"]?.arrayObject{
                        
                        NSUserDefaults.standardUserDefaults().setObject(dic, forKey: JoinKEYID(keyPath, customerId))
                        responseType = .ResponseList
                    }
                }
            }
            
        case Constants.foodPath:
            if let result = jsonResp?.dictionary{
                
                if let dic = result["data"]?.arrayObject{
                    dataFetchDict[keyPath] = NSDate()
                    
                    if let foodsDic = dic as? [[String:AnyObject]]{
                    
                        updateLocalFoods(foodsDic)
                        responseType = .ResponseList
                    }

                }
                
            }

            
        case Constants.recordPath:
            
            if let result = jsonResp?.dictionary{
                if let dic = result["data"]?.arrayObject{
                    
                    dataFetchDict[keyPath] = NSDate()
                    NSUserDefaults.standardUserDefaults().setObject(dic, forKey: JoinKEYID(keyPath, customerId))
                    responseType = .ResponseList
                    
                }else{
                
                    if let code = jsonResp?.dictionaryObject?["code"] as? Int{
                        
                        //更新本地记录
                        if code == 0{
                            
                            if let data = jsonResp?.dictionaryValue["data"]?.dictionaryObject{
                            
                                if  var localRecordDic =  NSUserDefaults.standardUserDefaults().objectForKey(JoinKEYID(keyPath,customerId)) as? [[String:AnyObject]]{
                                    var index  = -1
                                    
                                    if !localRecordDic.isEmpty{
                                    
                                        for k in 0...(localRecordDic.count - 1){
                                            
                                            if (localRecordDic[k]["id"] as! Int) == (data["id"] as! Int){
                                                
                                                localRecordDic[k] = data
                                                index = k
                                                break
                                            }
                                        }
                                    }
                                    
                                    switch method{
                                    
                                    case "DELETE":
                                        if index != -1{
                                        
                                            localRecordDic.removeAtIndex(index)
                                        }
                                        
                                    case "POST":
                                            localRecordDic.append(data)
                                    default:
                                        break
                                    }
                                    
                                    NSUserDefaults.standardUserDefaults().setObject(localRecordDic, forKey: JoinKEYID(keyPath, customerId))
                                }
                            }
                        }
                    }
                }
            }

            break
            
        default:
            break
        }
        
        if let dic = jsonResp?.dictionaryObject{
            if let code = dic["code"] as? Int{
            
                if code == 0{
                    NSNotificationCenter.defaultCenter().postNotificationName(Constants.kDataReflashNotification, object: nil, userInfo: ["keyPath" : keyPath,"responseType" : responseType.rawValue])
                }
            }
        }
    }
}

class InterfaceMode : NSObject,ASIHTTPRequestDelegate{
    
    var servResponseDelegete:ServerResponseDelegete?
    
    func setServerData(keyPath:String,paramDic:[String:AnyObject]){
    
        ASIReqeustData(paramDic, key: keyPath)
    }
    
    func ASIReqeustData(param:[String:AnyObject],key:String,method:String = "POST",block:Bool = false) ->NSData?{

           if let postURL = NSURL(string: Constants.url + key){
           let asiRequest = ASIPointRequest(URL: postURL)
            
            for item in param{
                
                print("key:\(item.0),value:\(item.1)")
                asiRequest.setPostValue(item.1 as! NSObject, forKey: item.0)
            }
            asiRequest.requestMethod = method
            if !block{
                asiRequest.keyString = key
                asiRequest.method = method
                asiRequest.delegate = self
                asiRequest.startAsynchronous()
            }else{
                
                asiRequest.startSynchronous()
                return asiRequest.responseData()
            }
        }
        
        return nil
    }
    
    func ASIGetOrDelData(id:Int?,key:String,method:String = "GET"){
        
        let idString = id == nil ? "" : id!.description
        let url = "\(Constants.url)\(key)/\(idString)"
        if let postURL = NSURL(string: url){
            
            let asiRequest = ASIPointRequest(URL: postURL)
            asiRequest.requestMethod = method
            asiRequest.delegate = self
            asiRequest.keyString = key
            asiRequest.method = method
            asiRequest.typeid = id
            asiRequest.startAsynchronous()
        }
        
    }
    
    func ASIGetServerData(path:String)->JSON?{
    
        if let postUrl = NSURL(string: Constants.url + path){
        
            let asiRequest = ASIHTTPRequest(URL: postUrl)
            asiRequest.requestMethod = "GET"
            asiRequest.startSynchronous()

            print("ASIGetServerData:\(path),response:\(asiRequest.responseString())")
            if let res = asiRequest.responseData(){

                return JSON(data: res)
            }
        }
        
        return nil
    }
    
    func ASIReqeustWithString(paramStr:String,key:String,method:String = "POST"){
        
        if let postURL = NSURL(string: Constants.url + key){
            let asiRequest = ASIPointRequest(URL: postURL)
            
           let urlEncodeStr =  paramStr.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
            
            asiRequest.postBody = NSMutableData(data: urlEncodeStr!.dataUsingEncoding(NSUTF8StringEncoding)!)
            asiRequest.requestMethod = method
            asiRequest.delegate = self
            asiRequest.keyString = key
            asiRequest.method = method
            asiRequest.startAsynchronous()
            
            
        }
    }
    
    func requestFailed(request: ASIHTTPRequest!) {
        
        dispatch_async(dispatch_get_main_queue()) {
            
            if let pointRequst  = request as? ASIPointRequest{
                
                self.servResponseDelegete?.ServerResponseWithJSON(pointRequst.keyString!,method: pointRequst.method, jsonResp: nil, errorMsg: "服务器请求失败!",typeid: nil)
           }
        }

    }
    func requestFinished(request: ASIHTTPRequest!) {
        
        dispatch_async(dispatch_get_main_queue()) {

            if let pointRequst  = request as? ASIPointRequest{
                
                print("keyPath:\(pointRequst.keyString),response:\(pointRequst.responseString())")
                
                if let response = pointRequst.responseString(){
                
                   let resetString = response.stringByReplacingOccurrencesOfString("null", withString: "\"\"", options: NSStringCompareOptions.LiteralSearch, range: nil)
                    
                    self.servResponseDelegete?.ServerResponseWithJSON(pointRequst.keyString!, method:pointRequst.method,jsonResp: JSON(data: resetString.dataUsingEncoding(NSUTF8StringEncoding)!), errorMsg: nil,typeid: pointRequst.typeid)
                    
                    return
                }else{
                
                    self.servResponseDelegete?.ServerResponseWithJSON(pointRequst.keyString!, method:pointRequst.method, jsonResp: nil, errorMsg: "服务器请求失败!",typeid: pointRequst.typeid)
                }
            }
            
            
        }
    }
    
    func ASIUploadImage(localPath:String,completion:((serverPath:String?) -> Void)?){
        
        if let postURL = NSURL(string: Constants.filePath){
            
            if let request = ASIFormDataRequest(URL: postURL){
                
                request.setPostValue("file", forKey: "type")
                request.setFile(localPath, forKey: "file")
                request.buildPostBody()
                request.startSynchronous()
                
                if let res = request.responseData(){
                    print(request.responseString())
                    let json = JSON(data: res)
                    if let dic = json.dictionaryObject{
                        completion?(serverPath: dic["data"] as? String)
                        
                        return
                    }
                }
            }
        }
        completion?(serverPath: nil)
    }
    
    func ASIGetServerImage(serverPath:String)->String?{
    
         let arrayNames = serverPath.componentsSeparatedByString("/")
        
        if let imageName = arrayNames.last{

            if let postURL = NSURL(string: serverPath){
                
                if let request = ASIHTTPRequest(URL: postURL){
                    
                    let localPath = "\(OCUtils.documentFolderPath())/\(imageName)"
                    request.downloadDestinationPath = localPath
                    request.startSynchronous()
                    if NSFileManager().fileExistsAtPath(localPath){
                        
                        return localPath
                    }
                }
            }
        }
        return nil
    }
}